linux命令行

您所在的位置:网站首页 linux 获取参数 linux命令行

linux命令行

2023-11-19 07:02| 来源: 网络整理| 查看: 265

linux命令行多个参数值解析方法 使用背景

如下命令行:

./test -a 123 --command 11 22 33 -f filename

一个简单的小应用程序,需要传入多个参数,有的参数甚至需要带有多个参数值 如何通过 getopt_long来获取需要多个参数值。

API介绍

getopt_long 函数原型:

int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex)

常规用法可以看这位大佬写的: 常规用法

实现传入多个参数

循环调用getopt_long会遍历所有的输出的参数,与传进去的longopts列表对比。

返回负数的时候,表示已经遍历完了或者出错了。

所以循环调用,直到返回负数之后break出来

每次调用,switch传入的参数,即可实现传入多个参数。

循环的示例 while (1) { opt = getopt_long(argc, argv, "p:", long_options, NULL); if (opt < 0) break; switch (opt) { case USER_OPT_1: {break;} case USER_OPT_2: {break;} } } longopts列表示例 static struct option long_options[] = { {"command1", required_argument, NULL, USER_OPT_1}, {"command2", required_argument, NUll, USER_OPT_2}, {0,0,0,0}, } 实现一个参数传入多个参数值

核心点是optind这个参数,这个参数代传入的argv列表,下一个将要被处理的参数值的下标

./test -a 123 --command 11 22 33 -f filename

在上面的指令中,当处理到 --command这个参数的时候,这个参数对应的参数值是11 optind指的是下一个将要被处理的参数值下标,也就是22的下标 所以当处理到–command的时候

argv[optind-1] = 11; argv[optind ] = 22; argv[optind+1] = 33; ./testoptoptargargv[optind ]-a12311–command1122-ffilenameNUll 传入多个参数值的代码示例 static struct option long_options[] = { {"help", required_argument, 0, USER_OPT_HELP}, {"test", required_argument, 0, USER_OPT_TEST}, , {0, 0, 0, 0} }; int main(int argc,char *argv[]) { while (1) { opt = getopt_long(argc, argv, "p:", long_options, NULL); if (opt < 0) break; switch (opt) { case USER_OPT_TEST: { printf("opt_0 = %d\n", atoi( argv[optind - 1])); printf("opt_1 = %d\n", atoi( argv[optind ])); printf("opt_2 = %d\n", atoi( argv[optind + 1])); printf("opt_4 = %s\n", argv[optind+2]); break; } } } return 0; }

执行结果



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3